package com.kunlong.test.fastdfs;

import com.kunlong.CodegenApp;
import com.kunlong.config.fastdfs.FastdfsConfig;
import com.kunlong.demo.domain.CodeDatasource;
import com.kunlong.demo.service.CodeDatasourceService;
import com.kunlong.fastdfs.dto.FastdfsFileInfoDto;
import com.kunlong.fastdfs.service.FastsdfsApiService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.FileCopyUtils;

import javax.sql.DataSource;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;

@RunWith(SpringRunner.class)
@SpringBootTest(classes= CodegenApp.class,webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class SpringBootAppTestFastdfs {

    @Autowired
    CodeDatasourceService codeDatasourceService;
    @Autowired
    FastsdfsApiService fastsdfsApiService;

    @Qualifier("codegenDataSource")
    @Autowired
    DataSource dataSource;

    @Test
    public void TestDb() throws SQLException {
        CodeDatasource codeDatasource = codeDatasourceService.findById(1);
        System.out.println(codeDatasource);
        String s = dataSource.getConnection().getSchema();
        System.out.println(s);
    }

    @Test
    public void testFastdfsUpload() {
        System.out.println(1);
        FastdfsFileInfoDto fileInfoDTO= fastsdfsApiService.upload("leijmdas","txt","{\"d\":1}".getBytes(),null);
        System.out.println(fileInfoDTO);
    }

    @Test public void testFastdfsUploadImage(){
        String filename = getClass().getResource("/test/testfile/1.JPG").getPath();
        File file = new File(filename);
        byte[] b= new byte[0];
        try {
            b = FileCopyUtils.copyToByteArray(file);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        FastdfsFileInfoDto fileInfoDTO= fastsdfsApiService.upload(filename,"jpg",b,null);
        System.out.println(fileInfoDTO);


    }
    @Autowired
    FastdfsConfig fastdfsConfig;
    @Test public void testFastdfsDeleteFile(){
        fastdfsConfig.getProps();
        String filename = getClass().getResource("/test/testfile/1.JPG").getPath();
        File file = new File(filename);
        byte[] b= new byte[0];
        try {
            b = FileCopyUtils.copyToByteArray(file);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        FastdfsFileInfoDto fileInfoDTO= fastsdfsApiService.upload(filename,"jpg",b,null);
        System.out.println(fileInfoDTO);

        int i=fastsdfsApiService.delete(fileInfoDTO.getGroup(),fileInfoDTO.getRemoteFileName());
        System.out.println(i);
    }
}